package com.xoa.util.archive;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.Arrays;

public class ArchiveUtils {

    /****
     * 第一种：配置ftp方式获取附件，上传格式
     * @param path 为附件完整路径，根据此值获取文件名、文件类型、文件内容加密数据
     * @param ftpPath 在ftp上的相对路径，文件的父级文件夹地址
     * @return
     */
    public static String getFtpAttachment(String path, String ftpPath) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("file",ftpPath);
        String ext = null;
        String md5 = null;
        String filetype = null;
        if (path != null && path.contains(".")){
            ext = path.substring(path.lastIndexOf(".")+1);
            filetype = ext;
            md5 = getMd5ByFile(new File(path));
        }
        String name = path.substring(path.lastIndexOf("/") + 1,path.lastIndexOf("."));
        jsonObject.put("name",name);
        jsonObject.put("ext",ext);
		jsonObject.put("filemd5",md5);
		jsonObject.put("filetype",filetype);
        //多个附件上传，数据格式获取方式同上，最终组成json数组
        return JSONArray.fromObject(jsonObject).toString();
    }

    /***
     * 第二种：配置服务器存储路径方式获取附件，上传格式
     * @param serverPath 在服务器上的存储位置，即相对于/filelog/接口id(appid)后面的路径
     * @return
     * @throws Exception
     */
    public static String getServerAttachment(String serverPath){
        JSONObject attachment = new JSONObject();
        attachment.put("name", serverPath.substring(serverPath.lastIndexOf("/") + 1,serverPath.lastIndexOf(".")));
        attachment.put("ext", serverPath.substring(serverPath.lastIndexOf(".") + 1));
        attachment.put("file", serverPath);
        return JSONArray.fromObject(attachment).toString();
    }

    /**
     * 第三种：配置接口数据流方式获取附件，上传格式
     * @param filePath 为附件完整路径
     * @return
     * @throws Exception
     */
    public static String getDataStreamAttachment(String filePath){
        JSONObject attachment = new JSONObject();
        attachment.put("name", filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf(".")));
        attachment.put("ext", filePath.substring(filePath.lastIndexOf(".") + 1));
        attachment.put("file", getFileContentByBase64(filePath));
        attachment.put("filemd5", getMd5ByFile(new File(filePath)));
        attachment.put("filetype",filePath.substring(filePath.lastIndexOf(".") + 1));
        //多个附件上传，数据格式获取方式同上，最终组成json数组
        return JSONArray.fromObject(attachment).toString();
    }


    /**
     * 对文件进行md5加密
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static String getMd5ByFile(File file){
        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(
                    FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    /**
     * 将文件以base64编码格式读取
     * @param filePath
     * @return
     */
    public static String getFileContentByBase64(String filePath) {
        StringBuffer sb = new StringBuffer();
        try {
            File file = new File(filePath);
            FileInputStream in = new FileInputStream(file);

            byte[] buf = new byte[3 * 1024 * 1024];
            int size;
            while ((size = in.read(buf)) != -1) {
                sb.append(Base64.encodeBase64String(Arrays.copyOf(buf, size)));
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

   /* public static void main(String[] args) {
        String ftpAttachment = getFtpAttachment("G:/docphp/uploads/filelog/wenjian/G10.2 Service.rar", "/2018/20180101/");
        System.out.println(ftpAttachment);
        String dataStreamAttachment = getDataStreamAttachment("F:/phpquest/uploads/filelog/wenjian/Service.rar");
        System.out.println(dataStreamAttachment);
        String serverAttachment = getServerAttachment("/phpquest/uploads/Service.rar");
        System.out.println(serverAttachment);
    }*/

}
